/**
 * Created by yujianfu on 2016/11/10.
 */
import * as React from 'react'
import {Popover, Card, Table, Icon, Collapse, Button, message, Popconfirm} from 'antd'
import {fetchPost} from '../../../../utils/request'
import styles from '../../../finance/photoCheck/common/detail/Index.less'
import Styles from '../../../finance/common/detail/Index.less'
import PhotoStyle from '../../less/Photo.less'
import Viewer from 'react-viewer'
import 'react-viewer/dist/index.css'

const Panel = Collapse.Panel

class Photo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      userId: props.userId,
      tradeNo: props.tradeNo,
      visible: false,
      activeIndex: 0,
      record: {},
      ocrAadhaar: null,
      ocrPan: null,
      stepType: props.stepType,
      reuploadRecord: null,
      reuploadTypeList: null,
      photoReUploadTime: props.photoReUploadTime,
      photoReUploadAllow: props.photoReUploadAllow,
    }
  }

  componentWillReceiveProps(props) {
    if (this.state.userId != props.userId || this.state.tradeNo != props.tradeNo) {
      this.setState({
        userId: props.userId,
        tradeNo: props.tradeNo,
        photoReUploadTime: props.photoReUploadTime,
        photoReUploadAllow: props.photoReUploadAllow,
      }, () => {
        this.getData()
        this.getReuploadRecord()
      })
    }
  }

  componentDidMount() {
    if (this.state.userId && this.state.tradeNo) {
      this.getData()
    }
  }

  getReuploadRecord() {
    if (this.state.tradeNo != null) {
      fetchPost(`/audit/photo/reupload/${this.state.tradeNo}/record`, {}).then(res => {
        if (res.code === 0) {
          if (res.data != null && res.data.list != null) {
            // console.log(res, 'audit photo reupload record ')
            this.setState({
                reuploadRecord: res.data.list,
              }, () => {
              }
            )
          }
        } else {
          message.error(res.msg)
        }
      })
    } else {
      this.setState({
        reuploadRecord: null,
      })
    }
  }

  getData() {
    this.setState({
      reuploadTypeList: null,
    }, () => {
      if (typeof (this.props.callbackParent) != 'undefined') {
        this.props.callbackParent(this.state.reuploadTypeList)
      }
    })

    if (this.state.tradeNo != null) {
      fetchPost(`/user/${this.state.tradeNo}/faceRecognition/info`, {}).then(res => {
        if (res.code === 0) {
          this.setState({
              record: res.data,
              //ocrAadhaar: res.data.ocrAadhaar,
              //ocrPan: res.data.ocrPan,
            }
            /*,
             () => {
             //this.props.changeParams({photoType: res.data.photoType})
             let aadhaarFrontImageUrl = this.state.record.aadhaarFrontImage[0].key
             let aadhaarBackImageUrl = this.state.record.aadhaarBackImage[0].key
             let panImageUrl = this.state.record.panImage[0].key
             let tradeNo = this.state.tradeNo
             fetchPost(`/user/faceRecognition/ocr/info`, {
             aadhaarFrontImageUrl,
             aadhaarBackImageUrl,
             panImageUrl,
             tradeNo
             }).then(res => {
             if (res.code === 0) {
             this.setState({
             ocrAadhaar: res.data.ocrAadhaar,
             ocrPan: res.data.ocrPan,
             })
             }
             })
             }*/
          )
        }
      })
    } else {
      this.setState({
        record: {}
      })
    }
  }

  createPhoto(photos, images, slf, msg, type) {
    if (photos == null || photos.length == 0) {
      return <span className="no-data"><Icon type='frown-o'/>{'No data'}</span>
    }
    let content = [];
    const self = this;
    let flag = 'NOTEMPTY';

    photos.map(function (item) {
      if (item.key == '' || item.key == null || item.key == ' ') {
        flag = 'EMPTY';
        return
      }

      let index = images.length
      images.push({src: item.key, alt: item.lastModified})
      content.push(
        <div key={Math.random().toString(16).substring(2)} style={{width: 200, display: 'inline-block'}}
             onClick={() => {
               slf.setState({visible: true, activeIndex: index})
             }}>
          <Card style={{width: 200}} bodyStyle={{padding: 0}} noHovering={true}>
            <div className={styles.customImage}>
              <img alt='reuploading' height='150' width='100%'
                   src={item.key + '?x-oss-process=image/resize,w_150'}/>
            </div>
          </Card>
        </div>
      )
    })


    let isPhotoCheckStep = false;
    if (self.props.stepType == 'photoCheckNew' ||
      self.props.stepType == 'photoCheckRepeat' ||
      self.props.stepType == 'photoCheckReupload') {
      isPhotoCheckStep = true;
    }

    // console.log(self.props.stepType, "self.props.stepType");

    // 仅在第二张照片后面添加按钮
    if (type != 'kycHidden') {
      if (flag == 'EMPTY') {
        content.push(<span className="no-data"><Icon type='frown-o'/>{'No data'}</span>)
      } else {
        if (isPhotoCheckStep) {
          if ((self.state.reuploadTypeList != null && self.state.reuploadTypeList.includes(type))
            || (self.state.photoReUploadAllow == null || self.state.photoReUploadAllow == 0)) {
            content.push(<Button type="primary" className={PhotoStyle.reuploadButton} disabled>Re-upload</Button>)
          } else {
            if (type == 'pan' || self.state.record.compareScore == null || self.state.record.compareScore < 60) {
              content.push(
                <Popconfirm placement='top' title='Are you sure this photo needs to be re-uploaded?'
                            onConfirm={this.reuploadPhotoMark.bind(this, type)}>
                  <Button type="primary" className={PhotoStyle.reuploadButton}>Re-upload</Button>
                </Popconfirm>
              )
            }
          }
        }
      }
    }

    return content
  }

  info() {
    const content = (
      <h3>
        <strong>Esc：Exit Full Screen&nbsp;&nbsp;← →:Switch picture &nbsp;&nbsp;↑ ↓:Zoom in and out  &nbsp;&nbsp;
          Ctrl+1:Reset  &nbsp;&nbsp;Ctrl+←
          →:Switch on one or the next one</strong>
      </h3>
    )

    return (
      <div>
        <span>Kyc Card(Front and Back)</span>
        <span style={{
          marginLeft: '10px',
          color: '#1ca5ed'
        }}>{'CardId: ' + (this.state.record.kycCardId == null ? 'NONE' : this.state.record.kycCardId)}</span>
        <span style={{
          marginLeft: '10px',
          color: '#1ca5ed'
        }}>{'DoB: ' + (this.state.record.dob == null ? 'NONE' : this.state.record.dob)}</span>
        <span style={
          {marginLeft: '10px'}
        }>Re-Upload Time: {this.state.photoReUploadTime}</span>
        <Popover content={content}>
          <Icon className='ml10' type='exclamation-circle-o'/>
        </Popover>
      </div>

    )
  }

  handHeld() {
    return (
      <div>
        <span>Selfie</span>
        <span style={{
          marginLeft: '10px',
          color: '#1ca5ed'
        }}>{'Compare Score: ' + (this.state.record.compareScore == null ? 'NONE' : this.state.record.compareScore)}</span>
      </div>

    )
  }

  reuploadPhotoMark = (type) => {
    let typeList = []
    if (this.state.reuploadTypeList != null) {
      typeList = this.state.reuploadTypeList
    }
    typeList.push(type)
    this.setState({
      reuploadTypeList: typeList,
    }, () => {
      console.log(this.state.reuploadTypeList, 'reuploadTypeList reuploadTypeList reuploadTypeList ======')
      if (typeof (this.props.callbackParent) != 'undefined') {
        this.props.callbackParent(this.state.reuploadTypeList)
      }
    })
  }

  createReuploadRecord(type) {
    if (this.state.reuploadRecord != null) {
      const columns = [{
        title: (<div style={{float: 'left'}}>{'Re-Upload Record'}</div>),
        colSpan: 3,
        dataIndex: 'time',
        key: 'time',
      }, {
        title: 'Remark',
        colSpan: 0,
        dataIndex: 'remark',
        key: 'remark',
      }, {
        title: 'Operator',
        colSpan: 0,
        dataIndex: 'operator',
        key: 'operator',
      }]
      let dataSource = []

      this.state.reuploadRecord.map(record => {
        if (record.type == type) {
          dataSource.push(
            {
              key: record.id,
              time: record.operationDate,
              remark: record.operationRemark,
              operator: record.operator,
            }
          )
        }
      })
      if (dataSource.length != 0) {
        return (<Table key={type} className={PhotoStyle.photoReuploadTable} dataSource={dataSource} columns={columns}
                       size="small" pagination={false} bordered={true}/>)
      }
    }
  }


  activeKey() {
    if (this.state.stepType === 'initialOrderNew') {
      return []
    } else {
      return ['1', '2', '3', '4']
    }
  }

  render() {
    if (this.state.record == null) {
      return <span className="no-data"><Icon type='frown-o'/>No data</span>
    }
    let images = []
    let slf = this

    return (
      <div className={styles.detailModule}>
        <Card
          title={'Photo Review ' + (this.state.record.kycType == null ? '' : ('[' + this.state.record.kycType + ']'))}
          bodyStyle={{padding: 0}} noHovering={true}>
          <Collapse defaultActiveKey={this.activeKey()}>
            <Panel header={this.info()} key='1'>
              <div style={{maxHeight: 255, overflow: 'auto'}}>
                {this.createPhoto(this.state.record.aadhaarFrontImage, images, slf, 'No aadhaar front', 'kycHidden')}
                {this.createPhoto(this.state.record.aadhaarBackImage, images, slf, 'No aadhaar back', 'kyc')}
                {this.createReuploadRecord('kyc')}
              </div>
            </Panel>
            <Panel header={this.handHeld()} key='2'>
              <div style={{maxHeight: 255, overflow: 'auto'}}>
                {this.createPhoto(this.state.record.aadhaarHandheldImage, images, slf, '', 'handheld')}
                {this.createReuploadRecord('handheld')}
              </div>
            </Panel>
            {/*<Panel header='Picture with Friends/Family' key='3'>
              <div style={{maxHeight: 255, overflow: 'auto'}}>
                {this.createPhoto(this.state.record.lifeImage, images, slf, '', 'selfie')}
                {this.createReuploadRecord('selfie')}
              </div>
            </Panel>*/}
            <Panel header='PAN Card' key='4'>
              <div style={{maxHeight: 255, overflow: 'auto'}}>
                {this.createPhoto(this.state.record.panImage, images, slf, '', 'pan')}
                {this.createReuploadRecord('pan')}
              </div>
            </Panel>
          </Collapse>
        </Card>
        <Viewer
          visible={this.state.visible}
          onClose={() => {
            this.setState({visible: false})
          }}
          images={images}
          activeIndex={this.state.activeIndex}
        />
      </div>

    )
  }
}

export default Photo
